<?php

namespace backend\controllers;

use Yii;
use yii\data\Pagination;
use common\models\base\AdWx;

class WxAccountController extends MController
{

    public function actionIndex()
    {
        $request = Yii::$app->request;
        $account = $request->get('account', '');
        // 关联角色查询
        $query = AdWx::find();
        if ($account) {
            $query->andWhere(['like', 'account', "%{$account}%"]);
        }
        $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => $this->_pageSize]);
        $models = $query->offset($pages->offset)
                ->orderBy(['id' => SORT_DESC])
                ->limit($pages->limit)
                ->all();
        return $this->render('index', [
                    'models' => $models,
                    'pages' => $pages,
                    'account' => $account,
        ]);
    }

    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id');
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            if ($request->isAjax) {
                Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
                return \yii\widgets\ActiveForm::validate($model);
            } else {
                return $model->save() ? $this->redirect(['index']) : $this->message($this->analysisError($model->getFirstErrors()), $this->redirect(['index']), 'error');
            }
        }

        return $this->render('edit', [
                    'model' => $model,
        ]);
    }

    public function actionDelete($id)
    {
        if ($this->findModel($id)->delete()) {
            return $this->message("删除成功", $this->redirect(['index']));
        } else {
            return $this->message("删除失败", $this->redirect(['index']), 'error');
        }
    }

    protected function findModel($id)
    {
        if (empty($id)) {
            return new AdWx;
        }
        if (empty($model = AdWx::findOne($id))) {
            return new AdWx;
        }

        return $model;
    }

}
